package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;
import com.loveto.constant.LovetoGiftAnims;
import com.loveto.model.GiftInfo;
import com.loveto.model.MemberInfo;

public class UserinfoViewOthersActivity extends BaseActivity implements
View.OnClickListener{
	
	// 사용하는 변수들
	private SharedPreferences pref;
	private Intent intentMoveToPage;
	private Handler myHandler = new Handler();
	private ProgressDialog progressDialog;
	private String memberid_other;
	private String memberid_mine;
	private String my_gender;
	private String other_gender;
	private String lookingTarget;
	private String isLikeUserStr = "";
	private boolean isLikeUser;
	
	private String errorMsg;
	private String suspend_date;
	private String suspend_reason;
	private String phone_uid;
	private boolean isSaveSuccess;
	
	private MemberInfo memberInfo;
	private List<AnimationDrawable> giftAnimList;
	private LovetoGiftAnims giftAnims = new LovetoGiftAnims();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_userinfo_view_others);
		
		//변수 선언
		progressDialog = new ProgressDialog(this);
		isLikeUser = false;
		isSaveSuccess = false;
		other_gender = "";
		
		giftAnimList = new ArrayList<AnimationDrawable>();
		
		//로컬에서 정보 받아오기
		pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid_mine = pref.getString("memberid", "");
		my_gender = pref.getString("gender", ""); //성별이 다를때 처리를 위한
		phone_uid = pref.getString("phone_uid", ""); //성별이 다를때 처리를 위한
		
		//전 엑티비티에서 정보 받아오기
		Intent intent = getIntent();
		memberid_other = intent.getStringExtra("memberid_other");
		if ("".equals(memberid_other)||memberid_other == null) {
			memberid_other = "김기용";
		}
		lookingTarget = intent.getStringExtra("lookingTarget");
		//호감유저 추가영역 일단 가리기
		RelativeLayout area_add_likeuser = (RelativeLayout) findViewById(R.id.area_add_likeuser);
		area_add_likeuser.setVisibility(RelativeLayout.GONE);
		
		// 클릭 리스너 달기
		RelativeLayout v_btn_add_likeuser = (RelativeLayout) findViewById(R.id.btn_add_likeuser);
		v_btn_add_likeuser.setOnClickListener(this);
		RelativeLayout v_btn_show_album = (RelativeLayout) findViewById(R.id.btn_show_album);
		v_btn_show_album.setOnClickListener(this);
		ImageView v_userinfo_photo = (ImageView) findViewById(R.id.userinfo_photo);
		v_userinfo_photo.setOnClickListener(this);
		RelativeLayout v_btn_goto_back = (RelativeLayout) findViewById(R.id.btn_goto_back);
		v_btn_goto_back.setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.btn_report_profile)).setOnClickListener(this);
		
		//유저, 선물 정보 받아오기
		if (isNetworkAvailableAndNotice()) {
			getUserInfo();
			getGiftInfo();
		}
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_show_album:
			showAlbum();
			break;
		case R.id.userinfo_photo:
			showAlbum();
			break;
		case R.id.btn_add_likeuser:
			if (isNetworkAvailableAndNotice()) {
				if (!isLikeUser) {
					setLikeUser();
				}
			}
			break;
		case R.id.btn_report_profile:
			showAlertReport();
			break;
		case R.id.btn_goto_back:
			finish();
			break;
		}
	}
	
	//유저 정보를 서버에서 받아옴
	private void getUserInfo() {
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						try {
							String jsonText = JsonUtils
									.getStringFromUrl(LovetoConstant.USERINFO_OTHER_URL + "?memberid_other=" + memberid_other + "&memberid_mine=" + memberid_mine);
							
							//Log.d("tag", jsonText);
							// 원격에서 읽어온 데이터로 JSON 객체 생성
							try {
								JSONArray jsonArray = new JSONArray(jsonText);
								JSONObject object = jsonArray.getJSONObject(0);
								
								memberInfo = new MemberInfo(object
										.getInt("innocent_cnt"), object
										.getInt("sexy_cnt"), object.getInt("cuty_cnt"),
										object.getInt("intelligent_cnt"), object
												.getInt("follower_cnt"),0, object
												.getString("introduce"), object
												.getString("age"), object
												.getString("local"), object
												.getString("local_detail"), object
												.getString("job"), object
												.getString("height"), object
												.getString("characters"), object
												.getString("look"), object
												.getString("hobby"), object
												.getString("favorite"), object
												.getString("idealtype"), object
												.getString("photo_url1"), object
												.getString("photo_url2"), object
												.getString("photo_url3"), object
												.getString("photo_url4"));
								
								other_gender = object.getString("gender");
								isLikeUserStr = object.getString("islikeuser");
								
								//사진 URL 저장
								Editor editor = pref.edit();
								editor.putString("looking_photo_url1", object.getString("photo_url1"));
								editor.putString("looking_photo_url2", object.getString("photo_url2"));
								editor.putString("looking_photo_url3", object.getString("photo_url3"));
								editor.putString("looking_photo_url4", object.getString("photo_url4"));
								editor.commit();
								
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						} finally {
							myHandler.post(new Runnable() {
								@Override
								public void run() {
									makeUserInfoLayout(memberInfo);
									progressDialog.dismiss();
								}
							});
						}
					}
				});
			}
		}).start();
	}
	
	
	private void setLikeUser() {
		//제목 받아오기
		progressDialog.setMessage("정보를 저장하고있습니다.");
		progressDialog.show();
		//마감 시간(스트링) 받아오기
		try {
			//서버에 정보 보내기
			StringBuffer url = new StringBuffer(LovetoConstant.USERINFO_ADDFOLLOW_URL);
			url.append("?user_following=").append(memberid_mine).append("&user_follower=").append(memberid_other).append("&phone_uid=").append(phone_uid);
			Log.d("tag", "url : " + url.toString());
			String jsonText = JsonUtils.getStringFromUrl(url.toString());
			Log.d("tag", "jsonText : " + jsonText);
			JSONObject object = new JSONObject(jsonText);
			String result = object.getString("result");
			String err = object.getString("err");
			suspend_date = object.getString("suspend_date");
			suspend_reason = object.getString("suspend_reason");
			Log.d("tag", "result : " + result);
			Log.d("tag", "err : " + err);
			if (!"F".equals(result)) {
				isSaveSuccess = true;
			} else {
				errorMsg = err;
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
			Log.d("tag", "setRoundInfo() error, " + e.getMessage());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Log.d("tag", "setRoundInfo() error, " + e.getMessage());
		} finally {
			if (isSaveSuccess) {
				showSimpleAlert("정보 저장에 성공했습니다.");
			} else if ("Incorrect PhoneID".equals(errorMsg)){
				//폰 인증정보가 틀린 경우
				showAlertIncorrectPhoneID(UserinfoViewOthersActivity.this);
			} else if ("SuspendedID".equals(errorMsg)) {
				//이용 정지 상태인 경우
				showAlertSuspendID(UserinfoViewOthersActivity.this, suspend_date, suspend_reason);
			} else {
				showSimpleAlert("데이터 저장에 실패했습니다. 다시 시도해주세요.");
			}
			getUserInfo();
			Log.d("tag", "getUserInfo() 호출");
		}
		//progressDialog.dismiss();
		Log.d("tag", "setLikeUser() end");
	}
	
	
	//애니메이션은 윈도우에 포커스가 간 뒤에 스타트 시켜야 제대로 나옴.
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		
		for (int i=0;i<giftAnimList.size();i++) {
			giftAnimList.get(i).start();
		}
		
	    super.onWindowFocusChanged(hasFocus);
	}
	
	private void getGiftInfo() {
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
							try {
								Log.d("tag", "getGiftInfo() start");
								String jsonText = JsonUtils.getStringFromUrl(LovetoConstant.GIFT_OWN_LIST + "?memberid=" + memberid_other);
								//Log.d("tag", "jsonText : " + jsonText);
								try {
									JSONArray jsonArray = new JSONArray(jsonText);
									for (int i = 0; i < jsonArray.length();i++) {
										JSONObject object = jsonArray.getJSONObject(i);
										GiftInfo giftInfo = new GiftInfo(object.getInt("giftid"), object.getString("category"), "", object.getString("size"), object.getString("name"), object.getInt("price"), 0, "");
										makeGiftLayout(giftInfo, object.getInt("own_cnt"));
									}
								} catch (JSONException e) {
									e.printStackTrace();
									Log.d("tag", "getGiftInfo() error, " + e.getMessage());
								}
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
								Log.d("tag", "getGiftInfo() error, " + e.getMessage());
							} finally {
							}
						}
				});
			}
		};
		new Thread(runnable).start();
	}
	
	private void makeGiftLayout(GiftInfo giftInfo,int giftOwnCnt) {
		
		//값 받아오기
		int giftid = giftInfo.getGiftid();
		String size = giftInfo.getSize();
		String name = giftInfo.getName();
		
		//그림 넣을 위치
		LinearLayout v_giftlist = (LinearLayout) findViewById(R.id.area_gift_list);
		RelativeLayout v_area_gift;
		if ("L".equals(size)) {
			v_area_gift = (RelativeLayout) getLayoutInflater().inflate(R.layout.loveto_gift_list_large, null);
		} else if ("M".equals(size)) {
			v_area_gift = (RelativeLayout) getLayoutInflater().inflate(R.layout.loveto_gift_list_medium, null);
		} else {
			v_area_gift = (RelativeLayout) getLayoutInflater().inflate(R.layout.loveto_gift_list_small, null);
		}
		ImageView image = (ImageView)v_area_gift.findViewById(R.id.gift_img);
		
		//그림에 애니메이션을 넣을지 그림을 넣을지 판단
		if (giftAnims.getGiftAnimMap().containsKey(giftid)) { 
			//로컬에 선물 아이디에 대한 애니메이션 리소스가 있으면
			image.setBackgroundResource(giftAnims.getGiftAnimMap().get(giftid)); //애니메이션 지정
			giftAnimList.add((AnimationDrawable)image.getBackground()); //애니메이션 배열에 추가 (나중에 한번에 start 하기 위해)
		} else {
			//현재 버전에 선물에 대한 애니메이션 리소스가 없으면 FTP 의 1장짜리 이미지로 대체함
			String url = LovetoConstant.GIFT_IMAGE_URL + giftid + ".png";
			Log.d("tag","선물 url: " + url);
			ImageDownloader imageDownloader = new ImageDownloader();
			imageDownloader.download(url, image);
		}
		
		//이름 달기
		((TextView)v_area_gift.findViewById(R.id.text_price)).setText(name);
		//개수 달기
		((TextView)v_area_gift.findViewById(R.id.text_point)).setText(giftOwnCnt+"개");
		//가격 아이콘 숨기기
		((ImageView)v_area_gift.findViewById(R.id.icon_gift_price_id)).setVisibility(ImageView.GONE);
		
		//선물 뷰에 추가하기
		v_giftlist.addView(v_area_gift);
	}
	
    private void showAlertReport() {
		new AlertDialog.Builder(this)
		.setTitle("신고")
		.setMessage("욕설/홍보/음란성/허위정보 등을 신고해주세요! 단,허위신고는 불이익을 받을 수 있습니다.")
		.setPositiveButton("신고", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				Intent intent = new Intent(UserinfoViewOthersActivity.this,ReportUserActivity.class);
				intent.putExtra("category", "profile");
				intent.putExtra("target_userID", memberid_other);
				intent.putExtra("tournamentID", 0);
				startActivity(intent);
			}
		})
		.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		})
		.show();
    }
    
    private void showAlbum() {
    	
    	//토너먼트 주최자 정보를 보러온 경우
    	if ("TournamentMaker".equals(lookingTarget)) {
    		if ("".equals(memberid_mine)) {
    			showSimpleAlertAndMoveChoice("로그인을 하지않으면 주최자의 앨범을 볼 수 없습니다. 로그인 하시겠습니까?", UserinfoViewOthersActivity.this, LoginMainActivity.class,"로그인");
    			return;
    		} else if (my_gender.equals(other_gender)) {
    			showSimpleAlert("같은 성별의 토너먼트 주최자의 앨범은 볼 수 없습니다.");
    			return;
    		}
    	}
    	
		intentMoveToPage = new Intent(UserinfoViewOthersActivity.this,UserinfoViewAlbumOthersActivity.class); 
		intentMoveToPage.putExtra("memberid", memberid_other);
		startActivity(intentMoveToPage);
    }
    
	private void makeUserInfoLayout (MemberInfo memberInfo) {
		
		//성별에 따른 배경 변경
		if ("M".equals(other_gender)) {
			((RelativeLayout)findViewById(R.id.userinfo_bg)).setBackgroundResource(R.drawable.bg_user_man);
			((ImageView)findViewById(R.id.photo_round)).setImageResource(R.drawable.bg_photo_round_man);
		} else {
			((RelativeLayout)findViewById(R.id.userinfo_bg)).setBackgroundResource(R.drawable.bg_user_woman);
			((ImageView)findViewById(R.id.photo_round)).setImageResource(R.drawable.bg_photo_round_woman);
		}
		
		TextView v_userinfo_id = (TextView) findViewById(R.id.userinfo_id);
		v_userinfo_id.setText(memberid_other);
		
		int innocent_cnt = memberInfo.getInnocent_cnt();
		int sexy_cnt = memberInfo.getSexy_cnt();
		int cuty_cnt = memberInfo.getCuty_cnt();
		int intelligent_cnt = memberInfo.getInnocent_cnt();
		int popularity_total = innocent_cnt + sexy_cnt + cuty_cnt + intelligent_cnt;
		TextView v_userinfo_popularity = (TextView) findViewById(R.id.userinfo_popularity);
		v_userinfo_popularity.setText("인기도 : " + popularity_total);
		TextView v_userinfo_popularity_detail = (TextView) findViewById(R.id.userinfo_popularity_detail);
		v_userinfo_popularity_detail.setText("(청순" + innocent_cnt + "/섹시" + sexy_cnt  + "/큐티" +  cuty_cnt +  "/지적" + intelligent_cnt + ")");
		TextView v_userinfo_likeusers = (TextView) findViewById(R.id.userinfo_likeusers);
		v_userinfo_likeusers.setText("호감 갖는 이 : " + memberInfo.getFollower_cnt() + "명");
		TextView v_userinfo_introduce = (TextView) findViewById(R.id.userinfo_introduce);
		String introduce = memberInfo.getIntroduce();
		if ("null".equals(introduce)||"".equals(introduce)) {
			v_userinfo_introduce.setText("인사말 :");
		} else {
			v_userinfo_introduce.setText("인사말 : " + introduce);
		}
		TextView v_userinfo_gender = (TextView) findViewById(R.id.userinfo_gender);
		if ("M".equals(other_gender)) {
			v_userinfo_gender.setText("남성");
		} else {
			v_userinfo_gender.setText("여성");
		}
		
		String age = memberInfo.getAge();
		TextView v_userinfo_age = (TextView) findViewById(R.id.userinfo_age);
		if ("null".equals(age)||"".equals(age)) {
			v_userinfo_age.setText("미설정");
			v_userinfo_age.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_age.setText(age);
			v_userinfo_age.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		String local = memberInfo.getLocal();
		String local_detail = memberInfo.getLocal_detail();
		TextView v_userinfo_local = (TextView) findViewById(R.id.userinfo_local);
		if ("null".equals(local)||"".equals(local)) {
			v_userinfo_local.setText("미설정");
			v_userinfo_local.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_local.setText(local + " " + local_detail);
			v_userinfo_local.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		String job = memberInfo.getJob();
		TextView v_userinfo_job = (TextView) findViewById(R.id.userinfo_job);
		if ("null".equals(job)||"".equals(job)) {
			v_userinfo_job.setText("미설정");
			v_userinfo_job.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_job.setText(job);
			v_userinfo_job.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		String height = memberInfo.getHeight();
		TextView v_userinfo_height = (TextView) findViewById(R.id.userinfo_height);
		if ("null".equals(height)||"".equals(height)) {
			v_userinfo_height.setText("미설정");
			v_userinfo_height.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_height.setText(height);
			v_userinfo_height.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		String characters = memberInfo.getCharacters();
		TextView v_userinfo_characters = (TextView) findViewById(R.id.userinfo_characters);
		if ("null".equals(characters)||"".equals(characters)) {
			v_userinfo_characters.setText("미설정");
			v_userinfo_characters.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_characters.setText(characters);
			v_userinfo_characters.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		String look = memberInfo.getLook();
		TextView v_userinfo_look = (TextView) findViewById(R.id.userinfo_look);
		if ("null".equals(look)||"".equals(look)) {
			v_userinfo_look.setText("미설정");
			v_userinfo_look.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_look.setText(look);
			v_userinfo_look.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		String hobby = memberInfo.getHobby();
		TextView v_userinfo_hobby = (TextView) findViewById(R.id.userinfo_hobby);
		if ("null".equals(hobby)||"".equals(hobby)) {
			v_userinfo_hobby.setText("미설정");
			v_userinfo_hobby.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_hobby.setText(hobby);
			v_userinfo_hobby.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		String favorite = memberInfo.getFavorite();
		TextView v_userinfo_favorite = (TextView) findViewById(R.id.userinfo_favorite);
		if ("null".equals(favorite)||"".equals(favorite)) {
			v_userinfo_favorite.setText("미설정");
			v_userinfo_favorite.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_favorite.setText(favorite);
			v_userinfo_favorite.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		String idealtype = memberInfo.getIdealtype();
		TextView v_userinfo_idealtype = (TextView) findViewById(R.id.userinfo_idealtype);
		if ("null".equals(idealtype)||"".equals(idealtype)) {
			v_userinfo_idealtype.setText("미설정");
			v_userinfo_idealtype.setTextColor(getResources().getColor(R.color.textGray));
		} else {
			v_userinfo_idealtype.setText(idealtype);
			v_userinfo_idealtype.setTextColor(getResources().getColor(R.color.textNormalBlack));
		}
		
		//사진 변경
		String photo_url1 = memberInfo.getPhoto_url1();
		if ("Y".equals(photo_url1)) {
			String url = LovetoConstant.PHOTO_THUMB_URL + memberid_other + ".jpg";
			ImageDownloader imageDownloader = new ImageDownloader();
			ImageView imgView = (ImageView) findViewById(R.id.userinfo_photo);
			imageDownloader.download(url, imgView);
		} else if ("M".equals(other_gender)) {
			((ImageView)findViewById(R.id.userinfo_photo)).setImageResource(R.drawable.photo_blank_man);
		} else {
			((ImageView)findViewById(R.id.userinfo_photo)).setImageResource(R.drawable.photo_blank_woman);
		}
		
		//호감 유저 추가하기 영역 설정
		RelativeLayout v_area_add_likeuser = (RelativeLayout) findViewById(R.id.area_add_likeuser);
		RelativeLayout v_btn_add_likeuser = (RelativeLayout) findViewById(R.id.btn_add_likeuser);
		TextView v_btn_add_likeuser_text = (TextView) findViewById(R.id.btn_add_likeuser_text);
		TextView v_add_likeuser_explain = (TextView) findViewById(R.id.add_likeuser_explain);
		if (!(other_gender.equals(my_gender))) { //성별이 다르면 보임 
			if ("N".equals(isLikeUserStr)) { //현재 호감 유저가 아니면
				v_btn_add_likeuser_text.setText("호감 이성으로 추가하기");
				v_add_likeuser_explain.setText("호감이성이 LOVETO 주최 시 쪽지로 받을 수 있습니다.");
			} else if ("Y".equals(isLikeUserStr)) {
				isLikeUser = true;
				v_btn_add_likeuser_text.setText("이미 호감이성으로 추가하였습니다.");
				v_add_likeuser_explain.setText("호감이성이 LOVETO 주최 시 쪽지로 받을 수 있습니다.");
				v_btn_add_likeuser.setBackgroundResource(R.drawable.bg_blank);
			}
			v_area_add_likeuser.setVisibility(RelativeLayout.VISIBLE); //호감 유저 정보 영역 보이기
		}
		
	}
}
